<?php

// namespace App\Worker;
// use \Workerman;

use \Workerman\Worker;

// echo getcwd();
require_once 'vendor/Workerman/Autoloader.php';
// require_once 'vendor/autoload.php';
/*
    make your worker happy please!
*/

// 当客户端连上来时分配uid，并保存连接，并通知所有客户端
function handle_connection($connection)
{
    // 为这个链接分配一个uid
    $connection->uid = ++$GLOBALS['global_uid'];
    $xxxxx = $GLOBALS['worker']->id . $connection->id;
    $GLOBALS['nameTable'][$xxxxx] = $connection->uid;
}

// 当客户端发送消息过来时，转发给所有人
function handle_message($connection, $data)
{
    $explode = explode(':', $data);
    if ($explode[0] == $data) {
    	return false;
    }
    $targetId = $explode[0];
    $message = $explode[1];
    foreach($GLOBALS['worker']->connections as $conn)
    {
        if ($conn->uid == $GLOBALS['nameTable'][$targetId]) {
            $conn->send("user[{$connection->uid}] said: $message");
        }
    }
}

// 当客户端断开时，广播给所有客户端
function handle_close($connection)
{
	if (count($GLOBALS['worker']->connections) == 0) {
		unset($GLOBALS['worker']);
		return 0;
	}
	unset($GLOBALS['nameTable'][array_search($connection->uid, $GLOBALS['nameTable'])]);

    foreach($GLOBALS['worker']->connections as $conn)
    {
        $conn->send("user[{$connection->uid}] logout");
    }
}

$global_uid = 0;
$nameTable = NULL;

// 创建一个文本协议的Worker监听12347接口
$text_worker = new Worker("text://0.0.0.0:12347");
// 只启动1个进程，这样方便客户端之间传输数据
$text_worker->count = 1;

$text_worker->onConnect = 'handle_connection';
$text_worker->onMessage = 'handle_message';
$text_worker->onClose = 'handle_close';

$GLOBALS['worker'] = $text_worker;
$GLOBALS['global_uid'] = $global_uid;
$GLOBALS['nameTable'] = $nameTable;
Worker::runAll('start', '');
// Worker::runAll('stop', '-d');
// Worker::runAll();